﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool : MonoBehaviour
{
    private static ObjectPool instance;
    public Dictionary<string, List<GameObject>> gameobjectPool = new Dictionary<string, List<GameObject>>();
    private ObjectPool() { }

    public static ObjectPool GetInstance()
    {
        return instance;
    }
    private GameObject gameManager;
    int Count;
    private void Awake()
    {
        instance = this;
    }

    //Return方法存储
    public void Return(GameObject go)
    {
        string key = go.name;
        if (!gameobjectPool.ContainsKey(key))
        {
            gameobjectPool[key] = new List<GameObject>() { go };
        }
        else
        {
            gameobjectPool[key].Add(go);
            //Debug.Log("进入对象池");
        }
        go.SetActive(false);
        //return go;
    }

    //get方法从对象池中获取

    public GameObject GetGO(string prefabname)
    {
        GameObject go;
        string key = prefabname + "(Clone)";
        //string key = prefabname;
        if (gameobjectPool.ContainsKey(key) && gameobjectPool[key].Count > 0)
        {
            Debug.Log("有key有物体初始化");
            List<GameObject> list = gameobjectPool[key];
            go = list[0];
            list.RemoveAt(0);
            //重新初始化状态
            go.SetActive(true);
        }
        else if (gameobjectPool.ContainsKey(key) && gameobjectPool[key].Count <= 0)
        {
            Debug.Log("有key无物体初始化");
            go = Instantiate(Resources.Load(prefabname)) as GameObject;
            go.SetActive(true);
        }
        else
        {
            Debug.Log("无key初始化");
            go = Instantiate(Resources.Load(prefabname)) as GameObject;
            go.SetActive(true);
            gameobjectPool.Add(key, new List<GameObject>() { });
        }
        return go;
    }
}
